import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import axios from "axios";
import style from "../css/PetDetail.css";
import { buy } from "../contracts/helper/nftMark.js";
import { Result } from "ethers";
export function PetDetail() {
  const { tokenId } = useParams();
  const [metadata, setMetadata] = useState("");

  useEffect(() => {
    const getInfo = async () => {
      const result = await axios.get(
        `http://127.0.0.1:3001/getPetInfo?tokenId=${tokenId}`
      );
      console.log(result.data[0]);
      setMetadata(result.data[0]);
    };
    getInfo();
  }, []);
  function handleAddress(addres) {
    const address = addres + "";
    const start = address.slice(0, 6);
    const end = address.slice(-4);
    return `${start}...${end}`;
  }
  async function handleBuyClick() {
    try {
      const result = await buy(tokenId);
      console.log(result.hash);
      if (result.hash) {
        axios.post("http://127.0.0.1:3001/buy", { tokenId: tokenId });
      }
    } catch (e) {
      console.error(e);
    }
  }
  return (
    <div className="nft-detail" style={style}>
      <div className="nft-image">
        <img src={metadata.images} alt={metadata.title} />
      </div>
      <div className="nft-info">
        <h3>{metadata.title}</h3>
        <p>{metadata.description}</p>
        <p>Seller: {handleAddress(metadata.seller)}</p>
        <p>Price: {metadata.price} USDT</p>
        <p>Token ID: {metadata.tokenId}</p>
        <button className="button-buy" onClick={handleBuyClick}>
          Buy
        </button>
      </div>
    </div>
  );
}
export default PetDetail;
